const messageSchema = require('../models/message')
const conversationSchema = require('../models/conversation')
const { v4: uuidv4 } = require('uuid');

const chat = {
    selectConversation: async (senderId, receiverId, msg) => {
        const query = {
            participator: {
                $all: [senderId, receiverId]
            }
        };
        const timestamp = new Date().getTime()
        const result = await conversationSchema.findOne(query);
        if (result == null) {
            const uuid = uuidv4();
            await conversationSchema.create({ participator: [senderId, receiverId], conversationId: uuid });
            await messageSchema.create({ conversationId: uuid, content: [{ senderId: senderId, receiverId: receiverId, timestamp: timestamp, msg: msg }] });
            return;
        }
        const message = await messageSchema.findOne({ conversationId: result.conversationId })
        message.content.push(
            { senderId: senderId, receiverId: receiverId, timestamp: timestamp, msg: msg }
        )
        await message.save()
        return;
    },
    getHistoryList: async (ctx, next) => {
        const { senderId, receiverId } = ctx.query;
        console.log(senderId, receiverId);
        const query = {
            participator: {
                $all: [senderId, receiverId]
            }
        };
        const timestamp = new Date().getTime()
        const result = await conversationSchema.findOne(query);
        if (result) {
            const message = await messageSchema.find({ conversationId: result.conversationId })
            console.log(message);
            let list = message[0].content
            const data = []
            list.forEach(item => {
                data.push({
                    id: item.senderId, msg: item.msg
                })
            })
            ctx.body = {
                code: 200,
                data: data
            }
        }
        return;

    }
}
module.exports = chat
